import 'package:sqflite/sqflite.dart';

import '../bt_database_helper.dart';
import '../models/bt_post.dart';

class BtPostProvider {
  late Database _db;

  BtPostProvider._internal() {
    _db = DatabaseHelper().database;
  }

  factory BtPostProvider() => _instance;

  static final BtPostProvider _instance = BtPostProvider._internal();

  Future<int> insert(BtPost post) async {
    int id = await _db.insert(tablePost, post.toMap());
    return id;
  }

  Future<BtPost?> getPost(String id) async {
    List<Map> maps = await _db.query(tablePost,
        columns: [
          columnAuthorId,
          columnAuthorName,
          columnAvatar,
          columnTitle,
          columnSubTitle,
          columnContent,
          columnFollowed,
          columnCover,
          columnPicUrls,
          columnComments,
          columnLikes,
          columnLikeStatuses,
          columnFollowStatuses,
          columnSenders
        ],
        where: '$columnAuthorId = ?',
        whereArgs: [id]);
    if (maps.isNotEmpty) {
      return BtPost.fromMap(maps.first as Map<String, dynamic>);
    }
    return null;
  }

  Future<int> delete(String id) async {
    return await _db.delete(tablePost, where: '$columnAuthorId = ?', whereArgs: [id]);
  }

  Future<int> update(BtPost post) async {
    return await _db
        .update(tablePost, post.toMap(), where: '$columnAuthorId = ?', whereArgs: [post.authorId]);
  }
}
